<template>
  <div class="user-list-container">
    <!-- 页面标题和搜索栏 -->
    <div class="page-header">
      <h2>用户信息列表</h2>
      <div class="search-bar">
        <el-input
          v-model="searchKey"
          placeholder="请输入用户名"
          clearable
          @keyup.enter="handleSearch"
        >
        </el-input>
        <div class="button-group"> 
         <el-button @click="handleSearch" class="margin1">搜索</el-button>
         <el-button @click="fanhui">返回</el-button>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="userList"
      border
      stripe
      size="small"
      style="width: 100%; margin-top: 20px"
      @sort-change="handleSortChange"
    >
      <el-table-column prop="id" label="ID" width="80"  />
      <el-table-column prop="userName" label="用户名"  />
      <el-table-column prop="password" label="密码"  />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="sex" label="性别" width="80">
        <template #default="scope">
          {{ scope.row.sex === 0 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="80">
        <template #default="scope">
          {{ scope.row.age || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址" />
      <el-table-column prop="createTime" label="创建时间" width="180" sortable>
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
     <el-table-column label="操作" width="120" align="center">
        <template #default="scope">
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
      

    <!-- 分页控件 -->
    <el-pagination
      v-if="userList.length > 0"
      class="pagination"
      background
      layout="total,  prev, pager, next, jumper"
      :current-page="currentPage"
      :total="total"
      :page-size="pageSize"
      @current-change="handleCurrentChange"
      
    />

    <!-- 空状态 -->
    <el-empty v-if="!loading && userList.length === 0" description="暂无用户数据" />

    <!-- 加载状态 -->
    <el-loading v-if="loading" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import axios from 'axios';
import { useRouter } from 'vue-router';


// 响应式数据
const allUsers = ref([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(15);
const searchKey = ref('');
const sortField = ref('');
const sortOrder = ref('');
const router = useRouter();

const userList = computed(() => {
  if (!searchKey.value.trim()) return allUsers.value;
  
  const keyword = searchKey.value.trim().toLowerCase();
  return allUsers.value.filter(user => 
    user.userName.toLowerCase().includes(keyword)
  );
});

// 生命周期钩子：组件挂载后加载数据
onMounted(() => {
  fetchUserList();
});

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true;
  
  try {
    const res = await axios.get('tCustomer/listc', {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        sortField: sortField.value, 
        sortOrder: sortOrder.value
      }
    });
     
    const apiData = res.data;
    
    if (apiData.code === 200) {
      const pageData = apiData.data;
      
      allUsers.value = pageData.records || [];
      total.value = pageData.total;
      currentPage.value = pageData.current;
      pageSize.value = pageData.size;
    } else {
      ElMessage.error(apiData.message || '获取用户列表失败');
    }
  } catch (err) {
    console.error('请求异常:', err);
    ElMessage.error('网络请求失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1; // 重置为第一页
};
function fanhui() {
  router.push("/umanage");
}



const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchUserList();
};

// 排序处理
const handleSortChange = ({ prop, order }) => {
  sortField.value = prop;
  sortOrder.value = order === 'ascending' ? 'asc' : 'desc';
  fetchUserList();
};

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};
const handleDelete = async (row) => {
  try {
    // 确认对话框
    await ElMessageBox.confirm(
      `确定要删除用户 "${row.userName}" 吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    loading.value = true;
    
   
    await axios.delete(`/tCustomer/listcD/${row.id}`);
    
    // 重新加载用户列表
    await fetchUserList();
    
    ElMessage.success('用户删除成功');
  } catch (error) {
    if (error !== 'cancel') { // 用户取消操作不提示错误
      console.error('删除用户失败', error);
      ElMessage.error('删除失败，查看订单是否完成');
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  display: flex; 
  align-items: center;
  gap: 8px; 
}

.button-group { 
  display: flex;
  gap: 8px; /* 按钮之间的间距 */
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
.margin1{
  margin-right: 10px;
}
</style>
